import {Button, Checkbox, Input, Modal, Pagination, Popconfirm, Space, Spin, Tag, Typography} from "antd";
import {useEffect, useState} from "react";
import RequestUtils from "../../utils/RequestUtils";
import Apis from "../../configs/Apis";
import {CloseOutlined, SaveOutlined, SearchOutlined} from "@ant-design/icons";
import {useNavigate} from "react-router-dom";

const {Title, Text, Paragraph} = Typography;

const AssignUserRoleModal = (props) => {
    // 从父组件接收的参数
    const {
        messageApi,
        userId,
        assignUserRoleModalVisible,
        setAssignUserRoleModalVisible,
        onSuccess,
        hasAssignedRoles
    } = props;

    // 分页查询角色请求参数
    const [pageQueryRoleReq, setPageQueryRoleReq] = useState({
        pageNum: 1,
        pageSize: 10,
        roleName: "",
        excludeRoleIds: Array.from(hasAssignedRoles).map(role => role.roleId)
    });

    // 分页查询角色返回实体
    const [pageQueryRoleResp, setPageQueryRoleResp] = useState({
        total: 0,
        pageCount: 0,
        records: []
    });

    // 所有可选角色列表
    const [allRoles, setAllRoles] = useState([]);
    // 已选中要分配的角色ID
    const [selectedRoleIds, setSelectedRoleIds] = useState([]);
    // 加载状态
    const [loading, setLoading] = useState(false);
    // 角色权限详情modal参数
    const [rolePermissions, setRolePermissions] = useState([]);

    // 当模态框显示或用户ID变化时重新加载数据
    useEffect(() => {
        if (assignUserRoleModalVisible && userId) {
            fetchAllData();
        }
    }, [assignUserRoleModalVisible, userId]);

    /**
     * 重新加载所有数据
     */
    const fetchAllData = () => {
        setLoading(true);
        // 并行请求角色列表和用户已分配角色
        Promise.all([
            fetchRoleList(),
            fetchAssignedRoles()
        ]).catch(err => {
            console.error("数据加载失败:", err);
        }).finally(() => {
            setLoading(false);
        });
    };

    /**
     * 获取角色列表 - 新增参数接收，确保使用最新分页参数
     */
    const fetchRoleList = (params) => {
        // 优先使用传入的参数，否则使用状态中的参数
        const queryParams = params || pageQueryRoleReq;

        return RequestUtils.post(Apis.permission.pageQueryRole, {
            pageNum: queryParams.pageNum,
            pageSize: queryParams.pageSize,
            roleName: queryParams.roleName,
            excludeRoleIds: Array.from(hasAssignedRoles).map(role => role.roleId)
        }).then(res => {
            setPageQueryRoleResp({
                total: res.total,
                pageCount: res.pageCount,
                records: res.records
            });
            setAllRoles(res.records);
            return res;
        }).catch(err => {
            messageApi.error("查询角色列表失败: " + err.message);
            throw err;
        });
    };

    /**
     * 获取用户已分配的角色
     */
    const fetchAssignedRoles = () => {
        return RequestUtils.post(Apis.permission.searchRoleRelationByUserId, {
            id: userId
        }).then(res => {
            // 提取已分配角色的ID
            const assignedRoleIds = res.relationRoles.map(role => role.id);
            setSelectedRoleIds(assignedRoleIds);
            return res;
        }).catch(err => {
            messageApi.error("查询已分配角色失败: " + err.message);
            throw err;
        });
    };

    /**
     * 根据角色id查询权限集合
     * @param roleId
     */
    const doSearchPermissionsByRoleId = (roleId) => {
        RequestUtils.post(Apis.permission.searchPermissionByRoleId, {
            id: roleId
        }).then(res => {
            setRolePermissions(res.permissionNames)
        }).catch(err => {
            messageApi.error("查询角色权限失败: ", err);
        })
    };

    /**
     * 处理角色选择变化
     */
    const handleRoleChange = (roleId, checked) => {
        if (checked) {
            // 添加角色（避免重复）
            if (!selectedRoleIds.includes(roleId)) {
                setSelectedRoleIds([...selectedRoleIds, roleId]);
            }
        } else {
            // 移除角色
            setSelectedRoleIds(selectedRoleIds.filter(id => id !== roleId));
        }
    };

    /**
     * 处理分页变化 - 修复核心：使用最新参数直接调用接口
     */
    const handlePageChange = (page, pageSize) => {
        // 创建新的查询参数
        const newParams = {
            ...pageQueryRoleReq,
            pageNum: page,
            pageSize: pageSize
        };

        // 更新状态
        setPageQueryRoleReq(newParams);

        // 直接使用新参数调用接口，不依赖状态更新
        fetchRoleList(newParams);
    };

    /**
     * 处理搜索
     */
    const handleSearch = () => {
        // 搜索时重置到第一页
        const newParams = {
            ...pageQueryRoleReq,
            pageNum: 1
        };
        setPageQueryRoleReq(newParams);
        fetchRoleList(newParams);
    };

    /**
     * 清除搜索条件
     */
    const handleClearSearch = () => {
        const newParams = {
            pageNum: 1,
            pageSize: 10,
            roleName: ""
        };
        setPageQueryRoleReq(newParams);
        fetchRoleList(newParams);
    };

    /**
     * 保存角色分配
     */
    const handleSave = () => {
        setLoading(true);
        RequestUtils.post(Apis.permission.assignRole2User, {
            userId: userId,
            roleIds: selectedRoleIds
        }).then(res => {
            messageApi.success("角色分配成功");
            setAssignUserRoleModalVisible(false);
            // 通知父组件刷新数据
            if (onSuccess && typeof onSuccess === 'function') {
                onSuccess();
            }
        }).catch(err => {
            messageApi.error("角色分配失败: " + err.message);
        }).finally(() => {
            setLoading(false);
        });
    };

    /**
     * 取消并关闭模态框
     */
    const handleCancel = () => {
        setAssignUserRoleModalVisible(false);
        // 重置状态
        resetModalState();
    };

    /**
     * 重置模态框状态
     */
    const resetModalState = () => {
        setSelectedRoleIds([]);
        setPageQueryRoleReq({
            pageNum: 1,
            pageSize: 10,
            roleName: ""
        });
        setAllRoles([]);
        setPageQueryRoleResp({
            total: 0,
            pageCount: 0,
            records: []
        });
    };

    // 样式定义
    const styles = {
        modalContent: {
            padding: '16px 0'
        },
        searchContainer: {
            marginBottom: '16px',
            display: 'flex',
            alignItems: 'center',
            gap: '12px',
            flexWrap: 'wrap'
        },
        input: {
            flex: '0 0 240px'
        },
        roleListContainer: {
            maxHeight: '300px',
            overflowY: 'auto',
            padding: '8px 0',
            marginBottom: '16px',
            border: '1px solid #f0f0f0',
            borderRadius: '4px',
        },
        roleItem: {
            display: 'flex',        // 使用Flex布局
            alignItems: 'center',   // 垂直居中对齐
            padding: '8px 12px',    // 适当添加内边距
            // 可以保留其他现有样式
        },
        roleName: {
            marginLeft: '8px',      // 与复选框保持距离
        },
        detailLink: {
            marginLeft: 'auto',     // 自动填充左侧空间，将元素推到右侧
            marginRight: '8px',     // 右侧留出一点空间
        },
        roleItemHover: {
            backgroundColor: '#f5f5f5'
        },
        selectedRolesContainer: {
            marginTop: '24px',
            paddingTop: '16px',
            borderTop: '1px dashed #e8e8e8'
        },
        selectedTags: {
            display: 'flex',
            flexWrap: 'wrap',
            gap: '8px',
            marginTop: '12px',
            maxHeight: '120px',
            overflowY: 'auto',
            padding: '8px',
            border: '1px solid #f0f0f0',
            borderRadius: '4px',
        },
        paginationContainer: {
            marginTop: '16px',
            textAlign: 'right'
        },
        loadingContainer: {
            textAlign: 'center',
            padding: '60px 0'
        },
        emptyText: {
            textAlign: 'center',
            padding: '40px 0',
            color: '#666'
        }
    };

    // 获取已选中的角色列表
    const selectedRoles = allRoles.filter(role =>
        selectedRoleIds.includes(role.id)
    );

    return (
        <Modal
            title={<Title level={5} style={{margin: 0}}>为用户分配角色</Title>}
            open={assignUserRoleModalVisible}
            onCancel={handleCancel}
            maskClosable={false}
            width={680}
            destroyOnClose={true}
            footer={[
                <Button
                    key="cancel"
                    danger
                    icon={<CloseOutlined/>}
                    onClick={handleCancel}
                    disabled={loading}
                >
                    取消
                </Button>,
                <Button
                    color="purple" variant="solid"
                    key="save"
                    icon={<SaveOutlined/>}
                    onClick={handleSave}
                    loading={loading}
                >
                    保存分配
                </Button>
            ]}
        >
            <div style={styles.modalContent}>
                {/* 搜索区域 */}
                <div style={styles.searchContainer}>
                    <Text strong>角色名称：</Text>
                    <Input
                        placeholder="请输入角色名关键词"
                        style={styles.input}
                        value={pageQueryRoleReq.roleName}
                        onChange={(e) => {
                            setPageQueryRoleReq({
                                ...pageQueryRoleReq,
                                roleName: e.target.value
                            });
                        }}
                        onPressEnter={handleSearch}
                    />
                    <Space>
                        <Button
                            type="primary"
                            icon={<SearchOutlined/>}
                            onClick={handleSearch}
                            disabled={loading}
                        >
                            查询
                        </Button>
                        {pageQueryRoleReq.roleName && (
                            <Button
                                icon={<CloseOutlined/>}
                                onClick={handleClearSearch}
                                disabled={loading}
                            >
                                清除
                            </Button>
                        )}
                        <Button
                            onClick={fetchAllData}
                            disabled={loading}
                        >
                            刷新
                        </Button>
                    </Space>
                </div>

                {/* 角色列表区域 */}
                <Title level={5} style={{margin: '0 0 12px 0'}}>可选角色列表</Title>

                {loading ? (
                    <div style={styles.loadingContainer}>
                        <Spin tip="加载角色数据中..." size="middle"/>
                    </div>
                ) : pageQueryRoleResp.records.length === 0 ? (
                    <Paragraph style={styles.emptyText}>
                        未找到匹配的角色，请尝试其他搜索条件
                    </Paragraph>
                ) : (
                    <>
                        <div style={styles.roleListContainer}>
                            {pageQueryRoleResp.records.map(role => (
                                <div
                                    key={role.id}
                                    style={styles.roleItem}  // 使用Flex布局
                                    onMouseEnter={(e) => {
                                        e.currentTarget.style.backgroundColor = '#f5f5f5';
                                    }}
                                    onMouseLeave={(e) => {
                                        e.currentTarget.style.backgroundColor = '';
                                    }}
                                >
                                    <Checkbox
                                        checked={selectedRoleIds.includes(role.id)}
                                        onChange={(e) => handleRoleChange(role.id, e.target.checked)}
                                        disabled={loading}
                                    />
                                    <Text style={styles.roleName}>{role.roleName}</Text>

                                    <Popconfirm
                                        styles={{width: '300px'}}
                                        title="角色关联的权限列表详情"
                                        description={
                                            rolePermissions.length > 0
                                                ? <div style={{
                                                    width: '300px',
                                                    display: 'flex',
                                                    flexWrap: 'wrap'
                                                }}>{rolePermissions.map(permission => (
                                                    <Tag key={permission.id}
                                                         style={{margin: '4px'}}
                                                         color="green"
                                                    >
                                                        {permission}
                                                    </Tag>
                                                ))}</div>
                                                : "暂无数据"
                                        }
                                        okText="确认"
                                        cancelText="关闭"
                                    >
                                        <a
                                            style={styles.detailLink}
                                            onClick={() => {
                                                doSearchPermissionsByRoleId(role.id)
                                            }}
                                        >权限详情</a>
                                    </Popconfirm>
                                </div>
                            ))}
                        </div>

                        {/* 分页控件 */}
                        <div style={styles.paginationContainer}>
                            <Pagination
                                current={pageQueryRoleReq.pageNum}
                                pageSize={pageQueryRoleReq.pageSize}
                                total={pageQueryRoleResp.total}
                                onChange={handlePageChange}
                                showSizeChanger
                                showQuickJumper
                                showTotal={(total) => `共 ${total} 个可选角色`}
                                disabled={loading}
                            />
                        </div>
                    </>
                )}

                {/* 已选角色区域 */}
                <div style={styles.selectedRolesContainer}>
                    <Title level={5} style={{margin: '0 0 12px 0'}}>
                        已选择角色 <span style={{color: '#1890ff'}}>({selectedRoles.length})</span>
                    </Title>

                    {selectedRoles.length === 0 ? (
                        <Paragraph style={{color: '#666', margin: 0}}>
                            尚未选择任何角色
                        </Paragraph>
                    ) : (
                        <div style={styles.selectedTags}>
                            {selectedRoles.map(role => (
                                <Tag
                                    key={role.id}
                                    color="blue"
                                    closable
                                    onClose={() => handleRoleChange(role.id, false)}
                                    disabled={loading}
                                >
                                    {role.roleName}
                                </Tag>
                            ))}
                        </div>
                    )}
                </div>
            </div>

        </Modal>
    );
};

export default AssignUserRoleModal;
